/**
 * Created by udi on 2016/11/26.
 */
'use strict'
var mongo = require('mongodb').MongoClient
var colors = require('colors');
let dbConfig = require("../../main/appConfig").mongoConfig;

var url = `mongodb://${dbConfig.host}:${dbConfig.port}/${dbConfig.database}`;

//记得最后  conn.close();
let getConn = async(callback) => {
  try {
    return await mongo.connect(url);
  }
  catch (err) {
    return console.error("mongo connecte Error:" + err);
  }
}


let mongo_find = async(tab, where) => {
  let db = await  getConn(url);
  if (!db) return;

  let collection = db.collection(tab);
  let docs;
  try {
    docs = await collection.find(where).toArray();
    return docs;
  }
  catch (err) {
    console.error("mongo find err:" + err);
  }
  finally {
    db.close();
  }
}

let mongo_findOne = async(tab,where)=>{
  let results=  await mongo_find(tab,where);
  return results && results[0];
}

let mongo_update = async(tab, where, updateEntity) => {
  let db = await  getConn(url);
  if (!db) return;

  let collection = db.collection(tab);
  let docs;
  try {
    docs = await collection.updateMany(where, updateEntity,true,true);
    return docs;
  }
  catch (err) {
    console.error("mongo find err:" + err);
  }
  finally {
    db.close();
  }
}

let mongo_insert = async(tab, entity) => {
  let db = await getConn(url);
  if (!db) return;

  let collection = db.collection(tab);
  let docs;
  try {
    docs = await collection.insert(entity);
    return docs;
  }
  catch (err) {
    console.error("mongo find err:" + err);
  } finally {
    db.close();
  }
}

let mongo_remove = async(tab, where) => {
  let db = await  getConn(url);
  if (!db) return;

  let collection = db.collection(tab);
  let docs;
  try {
    docs = await collection.remove(where);
    return docs;
  }
  catch (err) {
    console.error("mongo find err:" + err);
  } finally {
    db.close();
  }
}


let mongo_eval = async(command) => {
  let db = await  getConn(url);
  if (!db) return;

  let result;
  try {
    result = db.eval(tab);
    return result;
  }
  catch (err) {
    console.error("mongo eval err:" + command);
  } finally {
    db.close();
  }
}


exports.find = mongo_find;
exports.findOne = mongo_findOne;
exports.update = mongo_update;
exports.insert = mongo_insert;
exports.remove = mongo_remove;
exports.eval = mongo_eval;

